<template>
  <div class="update-main-box">
    <el-drawer
      :visible.sync="isDrawer"
      :direction="direction"
      :size="this.$store.state.user.userIsPhone ? '90%' : '800px'"
      :with-header="false"
      @close="defaultData"
    >
      <div class="drawer-title">
        <div class="drawer-title">修改证书信息</div>
        <div class="iconfont icon-guanbi" @click="isDrawer = false"></div>
      </div>
      <div class="head-box">
        <div class="identifier-box"></div>
        <div>证书信息</div>
      </div>
      <div class="form-box">
          <div class="left-box">
            <div class="info-box">
            <el-form :model="formData" :rules="rules" ref="ruleForm1" label-width="110px" class="demo-ruleForm">
              <el-form-item label="证书编号"  prop="fileCode">
                <el-input v-model="formData.fileCode" style="width: 92%;height: 100%;"></el-input>
              </el-form-item>
              <el-form-item label="公告编号"  prop="fileCode">
                <el-input v-model="formData.noticeCode" style="width: 92%;height: 100%;"></el-input>
              </el-form-item>
              <el-form-item  label="证书类型"  prop="fileType">
                <el-select v-model="formData.fileType" placeholder="请选择文件类型" filterable allow-create style="width: 92%;">
                  <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.dicvalue" :value="item.dickey"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="发证机关" prop="issueOrgan">
                  <el-input v-model="formData.issueOrgan" placeholder="请输入发证机关" style="width: 92%;height: 100%;"></el-input>
                  <!-- <el-select v-model="formData.issueOrgan" placeholder="请选择发证机关" filterable allow-create style="width: 92%;">
              <el-option v-for="(item, index) in organOptions" :key="index" :label="item.dicvalue" :value="item.dickey"></el-option>
            </el-select> -->
                </el-form-item>
              <el-form-item label="证书名称"  prop="fileName">
                <el-input v-model="formData.fileName" style="width: 92%;height: 100%;"></el-input>
              </el-form-item>
              <el-form-item label="证书简称"  >
                <el-input v-model="formData.fileShortName" style="width: 92%;height: 100%;"></el-input>
              </el-form-item>
              <el-form-item label="主要内容">
                <el-input v-model="formData.content" type="textarea" :autosize="{ minRows: 3, }" style="width: 92%;height: 100%;"></el-input>
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.notes" type="textarea" :autosize="{ minRows: 3, }" style="width: 92%;height: 100%;"></el-input>
              </el-form-item>
              </el-form>
          </div>
          </div>
          <div class="right-box"> 
            <div class="info-box">
            <el-form :model="formData" :rules="rules" ref="ruleForm2" label-width="110px" class="demo-ruleForm">
              <el-form-item label="申请日期"  >
                <el-date-picker v-model="formData.applyForTime" placeholder="请选择申请日期" :picker-options="pickerOptions"  style="width: 92%;height: 90%;margin-left: 5px;"></el-date-picker>
              </el-form-item>
              <el-form-item label="公告日期"  >
                <el-date-picker v-model="formData.noticeTime" placeholder="请选择公告日期" :picker-options="pickerOptions"  style="width: 92%;height: 90%;margin-left: 5px;"></el-date-picker>
              </el-form-item>
              <el-form-item label="下证日期"  >
                <el-date-picker v-model="formData.getTime" placeholder="请选择下证日期" :picker-options="pickerOptions"  style="width: 92%;height: 90%;margin-left: 5px;"></el-date-picker>
              </el-form-item>
              <el-form-item label="有效开始日期"  >
                <el-date-picker v-model="formData.beginTime" placeholder="请选择有效开始日期" :picker-options="pickerOptions"  style="width: 92%;height: 90%;margin-left: 5px;"></el-date-picker>
              </el-form-item>
              <el-form-item label="有效截止日期"  >
                  <el-date-picker v-model="formData.endTime" placeholder="请选择有效截止日期" :picker-options="pickerOptions"  style="width: 92%;height: 90%;margin-left: 5px;"></el-date-picker>
                </el-form-item>
              <el-form-item label="证书所属权" prop="unit">   
                <el-input v-model="formData.unit" type="textarea" style="width: 92%;height: 100%;"></el-input>  
              </el-form-item>
              <el-form-item label="证书所属人">
                <el-input v-model="formData.includPerson" type="textarea" style="width: 92%;height: 100%;"></el-input>
              </el-form-item>
              <!-- <el-form-item label="创建人">
                {{ formData.createName }}
              </el-form-item>
              <el-form-item label="创建时间">
                  {{ formData.createTime }}
              </el-form-item> -->
              </el-form>
          </div>
          </div>
        </div>
      <div class="head-box">
          <div class="identifier-box"></div>
          <div>附件信息</div>
        </div>
      <div class="anne-box">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :on-success="uploadSuccess"
          :multiple="false"
          :file-list="fileList"
        >
          <el-button size="small" type="success">附件上传</el-button>
        </el-upload>
      </div>
      <div class="head-box" style="height: 0"></div>
      <div class="btn-box">
        <div class="remove-btn" @click="cancellation('ruleForm')">取消</div>
        <div class="sub-btn" @click="determine('ruleForm')">提交</div>
      </div>
    </el-drawer>
    <DialogPreview ref="dialogPreviewRef" />
  </div>
</template>

<script>
import fixTime from '@/utils/fixTime.js'
import { getFilesListApi, delFilesApi, updateDetailDataApi } from '@/api/index'
import DialogPreview from './DialogPreview.vue'
export default {
  props: {
    drawer: {
      type: Boolean,
      default: false
    },
    projectRow: {
      type: Object,
      default: undefined
    },
    getAnnexListData: {
      type: Function,
      default: undefined
    },
    typeOptions: {
      type: Array,
      default: undefined
    },
    organOptions: {
      type: Array,
      default: undefined
    },
    unitOptions: {
      type: Array,
      default: undefined
    }
  },
  data () {
    var endTimeValidate = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        if (this.formData.getTime) {
          if (new Date(this.formData.getTime).getTime() > new Date(this.formData.endTime).getTime()) {
            callback(new Error('结束时间不能早于获取时间！'))
          }
          callback()
        }
        callback()
      }
    }
    var getTimeValidate = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        if (this.formData.beginTime) {
          if (new Date(this.formData.beginTime).getTime() > new Date(this.formData.getTime).getTime()) {
            callback(new Error('获得日期不能早于有效开始日期！'))
          }
          callback()
        }
        callback()
      }
    }
    return {
      // 项目编号
      proCode: '',
      // 是否弹出抽屉
      isDrawer: false,
      // 抽屉弹出方向
      direction: 'rtl',
      uploadUrl: 'apis/api/FilesUpload',
      // 原始数据
      rawData: {},
      formData: {
        // 编号
        fileCode: '',
        // 公告编码
        noticeCode: '',
        // 新增的名称
        fileName: '',
        // 新增的名称
        fileShortName: '',
        // 主要内容
        content: '', 
        // 备注
        notes: '', 
        // 下证日期
        getTime: '',
        // 申请日期
        applyForTime: '',
        // 申请日期
        noticeTime: '',
        // 有效开始日期
        beginTime: '',
        // 有效截止日期
        endTime: '',
        // 所属权
        unit: '',
        // 获取人
        includPerson: '',
        // 发证机构
        issueOrgan: '',
        // 创建人间
        createName: '',
        // 创建时间
        createTime: '',
        // 文件类型
        fileType: '',
        // 有效期
        validityTime: '',
        // 文件id
        fileGuid: ''
      },
      // 文件列表
      fileList: [],
      rules: {
        fileType: [
          { required: true, message: '请选择文件类型', trigger: 'blur' }
        ],
        fileCode: [
          { required: true, message: '请输入证书编号', trigger: 'blur' }
        ],
        fileName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 4, max: 100, message: '长度在 4 到 100 个字符', trigger: 'blur' }
        ],
        fileShortName: [
          { required: true, message: '请输入简称', trigger: 'blur' },
          { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入简称', trigger: 'blur' },
          { min: 4, max: 200, message: '长度在 4 到 200 个字符', trigger: 'blur' }
        ],
        issueOrgan: [ { required: true, message: '请输入发证机关', trigger: 'blur' } ],
        beginTime: [
          { required: true, message: '请有效截止日期', trigger: 'blur' },
          { validator: endTimeValidate, trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '请有效截止日期', trigger: 'blur' },
          { validator: endTimeValidate, trigger: 'blur' }
        ],
        getTime: [ { validator: getTimeValidate, trigger: 'blur' } ]
      },
      pickerOptions: {
        shortcuts: [ {
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        } ]
      }
    }
  },
  components: { DialogPreview },

  mounted () {},

  methods: {
    openDrawer (row) {
      this.rawData = { ...row }
      this.formData.fileCode = row.code
      this.formData.fileName = row.shortname
      this.formData.fileType = row.type
      this.formData.validityTime = row.validtime
      this.formData.fileGuid = row.guid
      this.formData.fileName = row.name
      this.formData.fileShortName = row.shortname
      this.formData.fileType = row.type
      this.formData.content = row.remark
      this.formData.notes = row.remark
      this.formData.applyForTime = row.gettime ? row.gettime : ''
      this.formData.noticeTime = row.noticetime ? row.noticetime : ''
      this.formData.noticeCode = row.noticecode ? row.noticecode : ''
      this.formData.getTime = row.gettime ? row.gettime : ''
      this.formData.beginTime = row.begintime  ? row.begintime : ''
      this.formData.endTime = row.finishtime ? row.finishtime : ''
      this.formData.unit = row.ownership
      this.formData.includPerson = row.participant
      this.formData.issueOrgan = row.certificateorgan
      this.formData.createName = row.creator
      this.formData.createTime = row.createtime
      console.log('编辑的-----》', row, this.formData)
      this.isDrawer = true
      this.getProFile(row.guid)
      this.uploadUrl = `apis/api/FilesUpload?detailguid=${row.guid}`
      let res = this.nameRules('awdadwa')
      console.log('正则验证-------->', res)
    },

    // 表单正则验证
    nameRules (value) {
      return /^(?!\d)[\u4e00-\u9fa5a-zA-Z0-9_-]{4,20}$/.test(value)
    },
    contentRules (value) {
      return /^(?!\d)[\u4e00-\u9fa5a-zA-Z0-9_-]{4,200}$/.test(value)
    },
    
    // 取消修改
    cancellation (formName) {
      this.formData.fileCode = this.rawData.code
      this.formData.fileName = this.rawData.shortname
      this.formData.fileType = this.rawData.type
      this.formData.validityTime = this.rawData.validtime
      this.formData.fileGuid = this.rawData.guid
      this.formData.fileName = this.rawData.name
      this.formData.fileShortName = this.rawData.shortname
      this.formData.fileType = this.rawData.type
      this.formData.content = this.rawData.remark
      this.formData.notes = this.rawData.remark
      this.formData.applyForTime = this.rawData.gettime ? this.rawData.gettime : ''
      this.formData.noticeTime = this.rawData.noticetime ? this.rawData.noticetime : ''
      this.formData.noticeCode = this.rawData.noticecode ? this.rawData.noticecode : ''
      this.formData.getTime = this.rawData.gettime ? this.rawData.gettime : ''
      this.formData.beginTime = this.rawData.begintime ? this.rawData.begintime : ''
      this.formData.endTime = this.rawData.finishtime ? this.rawData.finishtime : ''
      this.formData.unit = this.rawData.ownership
      this.formData.includPerson = this.rawData.participant
      this.formData.issueOrgan = this.rawData.certificateorgan
      this.formData.createName = this.rawData.creator
      this.formData.createTime = this.rawData.createtime
      this.$refs['ruleForm1'].resetFields()
      this.$refs['ruleForm2'].resetFields()
      this.isDrawer = false
    },
    // 确认修改
    async determine (formName) {
      console.log('确认修改---->', this.formData.getTime, this.formData.endTime, this.formData.beginTime)
      this.$refs['ruleForm1'].validate(async valid1 => {
        if (!valid1) {
          console.log('error submit!!')
          return false
        }
        this.$refs['ruleForm1'].validate(async valid2 => {
          if (valid1 && valid2) {
            let data = {
              noticecode: this.formData.noticeCode,
              empcode: this.$store.state.user.userCode,
              guid: this.formData.fileGuid,
              name: this.formData.fileName,
              shortname: this.formData.fileShortName,
              type: this.formData.fileType,
              maincontent: this.formData.content,
              applicationdate: fixTime(this.formData.applyForTime).split(' ')[0],
              noticetime: fixTime(this.formData.noticeTime).split(' ')[0],
              remark: this.formData.notes,
              gettime: fixTime(this.formData.getTime).split(' ')[0],
              begintime: fixTime(this.formData.beginTime).split(' ')[0],
              finishtime: fixTime(this.formData.endTime).split(' ')[0],
              ownership: this.formData.unit,
              participant: this.formData.includPerson,
              certificateorgan: this.formData.issueOrgan,
              creator: this.formData.createName,
              createtime: fixTime(this.formData.createTime).split(' ')[0]
            }
            let res = await updateDetailDataApi(data)
            if (res) {
              this.isDrawer = false
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              let data = {
                skipcount: 0,
                maxresultcount: 10
              }
              this.getAnnexListData(data)
            } else {
              this.$message({
                type: 'success',
                message: '修改失败!'
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
        
      })
    },

    // 获取当前项目的文件列表
    async getProFile (code) {
      let data = {
        detailguid: code
      }
      let res = await getFilesListApi(data)
      this.fileList = []
      res.forEach(item => {
        this.fileList.push({
          name: item.name,
          url: item.guid,
          guid: item.guid
        })
      })
      console.log('文件列表---------->', res, this.fileList)
    },
    // 文件列表移除文件时的钩子
    handleRemove (file, fileList) {
      
      console.log('删除附件----->', file, fileList, file.guid)
      this.delProFile(file.guid)
    },
    // 点击文件列表中已上传的文件时的钩子
    async handlePreview (file) {
      this.$refs.dialogPreviewRef.showDialog(file)
      // let data = { guid: file.guid }
      // let res = await downloadFileApi(data)
      // console.log('点击的文件--->', file, res)
      // const a = document.createElement('a')
      // a.style.display = 'none'
      // a.href = `http://192.168.8.181:925/api/FilesDownload?guid=${file.guid}`
      // a.click()
      // document.body.remove(a)
      // setTimeout(() => {
      //   this.$router.go(0)
      // }, 100)
    },
    // 限制文件大小
    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      )
    },
    // 文件上传成功
    uploadSuccess (response, file, fileList) { 
      
    },
    // 文件删除之前
    beforeRemove (file, fileList) {
      console.log('删除附件----->', file.guid)
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 删除文件
    async delProFile (id) {
      if (!id) return
      let data = {
        guid: id
      }
      console.log('删除附件----->', data, id)
      let res = await delFilesApi(data)
    },

    defaultData () {
      this.fileList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.update-main-box {
  .drawer-title {
    display: flex;
    justify-content: space-between;
    margin-top: 5px;
    margin-left: 5px;
    padding: 5px;
    padding-right: 15px;
    font-size: 16px;
    > div {
      font-weight: bold;
    }
    .icon-guanbi:hover {
      cursor: pointer;
    }
  }
  .head-box {
    display: flex;
    align-items: center;
    height: 30px;
    margin-top: 10px;
    margin-bottom: 10px;
    padding-left: 20px;
    font-size: 13px;
    line-height: 30px;
    text-align: start;
    border-bottom: 1px solid #dddcdc;
    .identifier-box {
      width: 5px;
      height: 10px;
      margin-right: 6px;
      background: #11a70c;
    }
  }
  .form-box {
    display: flex;
    justify-content: space-around;
  }
  .info-box {
    display: flex;

    /* border: 1px solid red; */
    >div {
      height: 100%;

      /* border: 1px solid green; */
      >div {
        display: flex;
        align-items: center;
        justify-content: space-around;
        height: 30px;
        margin-top: 10px;
      }
    }
    .left-box {
      width: 25%;
      >div {
        justify-content: flex-end;
        font-size: 12px;
      }
    }
    .right-box {
      width: 60%;
      .file-id-box {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
  .anne-box {
    display: flex;

    /* border: 1px solid red; */
    width: 100%;
    margin-top: 10px;
    padding-left: 8%;
    .upload-demo {
      /* border: 1px solid red; */
      width: 100%;
      text-align: start;
      .upload-btn {
        color: #000;
        background: rgba($color: #000, $alpha: 0%);
        border: none;
      }
      > ul::-webkit-scrollbar {
        width: 4px;
        height: 8px;
      }
      > ul::-webkit-scrollbar-thumb {
        background: fade(rgb(78 182 214), 60%);
        border-radius: 10px;
        box-shadow: inset 0 0 5px rgb(0 0 0 / 20%);
        opacity: 0.2;
      }
      > ul::-webkit-scrollbar-track {
        background: fade(rgb(78 182 214), 30%);
        border-radius: 0;
        box-shadow: inset 0 0 5px rgb(0 0 0 / 20%);
      }
    }
  }
  .btn-box {
    display: flex;
    justify-content: flex-end;
    width: 100%;
    margin: 10px 0;
    padding-right: 10px;

     /* border: 1px solid #c40f0f; */
    > div {
      width: 60px;
      height: 32px;
      margin-left: 10px;
      color: #fff;
      font-size: 12px;
      line-height: 32px;
      text-align: center;
      background: #85ce61;
      border-radius: 5px;
    }
    > div:hover {
      background: rgba($color: #85ce61, $alpha: 80%);
      cursor: pointer;
    }
    .sub-btn {
      color: #fff;
      background: #67c23a;
    }
    .sub-btn:hover {
      color: #fff;
      background: #85ce61;
      border-color: #85ce61;
      cursor: pointer;
    }
    .remove-btn {
      color: #000;
      background: rgba($color: #000, $alpha: 0%);
      border: 1px solid #dcdfe6;
    }
    .remove-btn:hover {
      color: #409eff;
      background-color: #ecf5ff;
      border-color: #c6e2ff;
      cursor: pointer;
    }
  }
}

@media screen and (width <= 768px) {
  .main-box {
    background: #ee0909;
  }
}
</style>